package com.hongri.recyclerview.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.hongri.recyclerview.R;
import com.hongri.recyclerview.utils.Logger;

/**
 * Created by zhongyao on 2016/12/17.
 *
 * 自定义属性步骤：
 * 1、value文件夹下创建自定义属性的xml（比如attrs.xml）
 * 2、在View的构造方法中解析自定义属性的值并做相应的处理
 * 3、在布局文件中使用改自定义属性
 */

public class CircleView extends View {
    private int mColor;
    private Paint mPaint;
    private final int WIDTH = 400,HEIGHT = 400;
    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint = new Paint();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
        mColor = array.getColor(R.styleable.CircleView_circle_color, Color.RED);
        array.recycle();

        init();
    }

    private void init() {
        mPaint.setColor(mColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpceSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        Logger.d("widthSpecMode:"+widthSpecMode+"widthSpceSize："+widthSpceSize+"heightSpecMode："+heightSpecMode+"heightSpecSize："+heightSpecSize);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(WIDTH,HEIGHT);
        }else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(WIDTH,heightSpecSize);
        }else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpceSize,HEIGHT);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();

        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingTop - paddingBottom;
        int radius = Math.min(width,height)/2;
        canvas.drawCircle(paddingLeft+width/2,paddingTop+height/2,radius,mPaint);
    }
}
